import React, {useState} from 'react';
import {Card, Input, Button, Modal} from 'antd';
import {EditOutlined, DeleteOutlined} from '@ant-design/icons';

import SchoolEditor from '../../component/schoolEditor';
import {eventBusPromise as eventBus} from '../../helpers/eventBus';
import * as schoolApi from '../../apis/school';
import useDidUpdate from '../../hooks/useDidUpdate';
import useGlobal from '../../hooks/useGlobal';
import useDidMount from '../../hooks/useDidMount';

function School() {

  const Global = useGlobal();

  useDidMount(() => {
    getList();
  }, []);

  // 查找
  const [list, setList] = useState([]);
  const [visibleList, setVisibleList] = useState(list);
  const [keyword, setKeyword] = useState('');

  const getList = () => {
    schoolApi.getList(Global.state.login?.token).then(res => {
      setList(res.data.data.list);
      Global.effect.updateSchoolList(res.data.data.list);
    });
  };

  const handleEdit = (school) => {
    // console.log(school);
    Modal.confirm({
      title: '修改高校',
      icon: null,
      content: <SchoolEditor school={school} onConfirm={async editorState => {
        const res = await schoolApi.update(Global.state.login?.token || '', {
          ...school,
          ...editorState,
        });
        if (res.data.code === 1) {
          setList(list.map(item => item.id === school.id ? {...school, ...editorState} : item));
        }
      }}/>,
      onOk: async () => {
        await eventBus.emit('schoolEditConfirm');
      }
    });
  };

  const handleAdd = () => {
    Modal.confirm({
      title: '修改高校',
      icon: null,
      content: <SchoolEditor onConfirm={async editorState => {
        const res = await schoolApi.add(Global.state.login?.token || '', {
          ...editorState,
        });
        if (res.data.code === 1) {
          setList([...list, res.data.data]);
        }
      }}/>,
      onOk: async () => {
        await eventBus.emit('schoolEditConfirm');
      }
    });
  };

  const handleDelete = (id, name) => {
    Modal.confirm({
      title: '确认删除高校',
      content: `删除${name}后${name}对应数据都会丢失，请谨慎操作`,
      onOk: async (close) => {
        const res = await schoolApi.del(Global.state.login?.token || '', id);
        if (res.data.code === 1) {
          setList(list.filter(item => item.id !== id));
          close();
        }
      }
    });
  };

  useDidUpdate(() => {
    setVisibleList(list.filter(item => item.name?.indexOf(keyword) >= 0))
  }, [keyword, list]);

  return (
    <div style={{padding: '40px'}}>
      <div className='top-bar' style={{textAlign: 'center', marginBottom: '20px'}}>
        <Input placeholder="搜索高校" style={{width: '400px'}} value={keyword} onChange={e => setKeyword(e.target.value)}/>
        <Button type='ghost' onClick={handleAdd} style={{marginLeft: '40px'}}>添加</Button>
      </div>

      <div className='list'>
        {
          visibleList.map((i, index) => {
            return (
              <Card key={index} style={{display: 'inline-block', width: 200, margin: '10px'}}
                    bodyStyle={{padding: '10px'}} hoverable={true}
                    actions={[
                      <EditOutlined onClick={() => handleEdit(i)}/>,
                      <DeleteOutlined onClick={() => handleDelete(i.id, i.name)}/>
                    ]}
              >
                <p style={{textAlign: 'center', margin: '20px 0', fontWeight: 'bold'}}>{i.name}</p>
              </Card>
            );
          })
        }
      </div>
    </div>
  );
}

export default School;